import AlcoholDevice from "@/components/devices/AlcoholDevice";
import CardiovascularDevice from "@/components/devices/CardiovascularDevice";
import DynamometerDevice from "@/components/devices/DynamometerDevice";
import VitalCapacityDevice from "@/components/devices/VitalCapacityDevice";
import {TestResult, useTestResults} from "@/contexts/TestResultsContext";
import {DataApi, DataVO, StandardApi, StandardVO, UserVo} from "@/utils/api";
import {
    calculateAlcoholScore,
    calculateBloodPressureScore, calculateFatigueIndex,
    calculateFlickerScore,
    calculateGripStrengthScore,
    calculateHealthIndex,
    calculateHeartAttackRiskScore, calculateLevel, calculateOverallIndex,
    calculateReactionTimeScore,
    calculateScore,
    calculateSpo2Score,
    calculateStressIndexScore,
    calculateVitalCapacityScore
} from "@/utils/score";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {useRouter} from 'expo-router';
import React, {useEffect, useState} from 'react';
import {
    Alert,
    Dimensions,
    Image,
    SafeAreaView,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';

// 心血管设备专用显示组件
const CardiovascularResultDisplay: React.FC<{ testResult: TestResult, standardData?: StandardVO }> = ({
                                                                                                          testResult,
                                                                                                          standardData
                                                                                                      }) => {
    const getStatusColor = (status: string) => {
        switch (status) {
            case 'normal':
                return '#4CAF50';
            case 'warning':
                return '#FF9800';
            case 'danger':
                return '#F44336';
            default:
                return '#999';
        }
    };

    const evaluateStatus = (value: any, key: string) => {
        if (!standardData) return 'normal';

        switch (key) {
            case 'heartRate':
                const hr = Number(value);
                if (hr < standardData.heartRate * 0.7 || hr > standardData.heartRate * 1.3) return 'danger';
                if (hr < standardData.heartRate * 0.8 || hr > standardData.heartRate * 1.2) return 'warning';
                return 'normal';
            case 'systolic':
                const systolic = Number(value);
                if (systolic >= 160) return 'danger';
                if (systolic >= 140) return 'warning';
                return 'normal';
            case 'diastolic':
                const diastolic = Number(value);
                if (diastolic >= 100) return 'danger';
                if (diastolic >= 90) return 'warning';
                return 'normal';
            case 'stressIndex':
                const stressIndex = Number(value);
                if (stressIndex > 80) return 'danger';
                if (stressIndex > 60) return 'warning';
                return 'normal';
            case 'heartAttackIndex':
                const heartAttackIndex = Number(value);
                if (heartAttackIndex > 30) return 'danger';
                if (heartAttackIndex > 15) return 'warning';
                return 'normal';
            case 'spo2':
                const spo2 = Number(value);
                if (spo2 < 90) return 'danger';
                if (spo2 < 95) return 'warning';
                return 'normal';
            default:
                return 'normal';
        }
    };

    // 提取所有测量值
    const measurementValues = testResult.measurement.value || {};

    // 定义要显示的指标及其顺序
    const indicators = [
        {key: 'heartRate', label: '心率', unit: 'bpm'},
        {key: 'spo2', label: '血氧', unit: '%'},
        {key: 'systolic', label: '收缩压', unit: 'mmHg'},
        {key: 'diastolic', label: '舒张压', unit: 'mmHg'},
        {key: 'stressIndex', label: '压力指数', unit: '%'},
        {key: 'heartAttackIndex', label: '心康指数', unit: '%'},
    ];

    // 获取所有测试结果，以便从不同的子设备中提取数据
    const {testResults} = useTestResults();
    const allTestResults = testResults || {};

    // 从所有心血管相关设备中提取指标值
    const getIndicatorValue = (indicatorKey: string) => {
        // 指标键名映射表，支持多种键名变体
        const keyVariants: Record<string, string[]> = {
            'heartRate': ['heartRate', 'HeartRate', 'pulse', '心率'],
            'spo2': ['spo2', 'SpO2', 'oxygenSaturation', '血氧'],
            'systolic': ['systolic', '收缩压'],
            'diastolic': ['diastolic', '舒张压'],
            'stressIndex': ['stressIndex', 'hrv', '压力指数'],
            'heartAttackIndex': ['heartAttackIndex', 'myocardialInfarctionIndex', 'st', '心康指数'],
        };

        // 获取当前指标的所有可能键名变体
        const variants = keyVariants[indicatorKey] || [indicatorKey];

        // 首先尝试从当前设备获取
        if (typeof measurementValues === 'object' && measurementValues !== null) {
            // 检查直接键名
            for (const variant of variants) {
                if (measurementValues[variant] !== undefined) {
                    return measurementValues[variant];
                }
            }

            // 不区分大小写的键名匹配
            if (typeof measurementValues === 'object') {
                for (const [key, value] of Object.entries(measurementValues)) {
                    if (variants.some(variant => key.toLowerCase() === variant.toLowerCase())) {
                        return value;
                    }
                }
            }
        }

        // 尝试从其他心血管子设备获取
        // 心率和血氧相关指标
        if (indicatorKey === 'heartRate' || indicatorKey === 'spo2') {
            const spo2Result = allTestResults['Cardiovascular_SpO2'];
            if (spo2Result?.measurement?.value) {
                const spo2Values = spo2Result.measurement.value;
                for (const variant of variants) {
                    if (spo2Values[variant] !== undefined) {
                        return spo2Values[variant];
                    }
                }
            }
        }

        // 血压相关指标
        if (indicatorKey === 'systolic' || indicatorKey === 'diastolic') {
            const bpResult = allTestResults['Cardiovascular_BP'];
            if (bpResult?.measurement?.value) {
                const bpValues = bpResult.measurement.value;
                for (const variant of variants) {
                    if (bpValues[variant] !== undefined) {
                        return bpValues[variant];
                    }
                }
            }
        }

        // ECG相关指标
        if (indicatorKey === 'stressIndex' || indicatorKey === 'heartAttackIndex') {
            const ecgResult = allTestResults['Cardiovascular_ECG'];
            if (ecgResult?.measurement?.value) {
                const ecgValues = ecgResult.measurement.value;
                for (const variant of variants) {
                    if (ecgValues[variant] !== undefined) {
                        return ecgValues[variant];
                    }
                }
            }
        }

        return null;
    };

    return (
        <View style={styles.cardioContainer}>
            {indicators.map((indicator, index) => {
                const value = getIndicatorValue(indicator.key);

                if (value === null || value === undefined) return null;

                const status = evaluateStatus(value, indicator.key);

                return (
                    <View key={index} style={styles.cardioItem}>
                        <Text style={styles.cardioLabel}>{indicator.label}</Text>
                        <Text style={[styles.cardioValue, {color: getStatusColor(status)}]}>
                            {value}
                        </Text>
                    </View>
                );
            })}
        </View>
    );
};

// 设备卡片组件
interface DeviceCardProps {
    title: string;
    status?: 'active' | 'coming_soon' | 'completed';
    onPress?: () => void;
    onRetest?: () => void;
    icon?: string;
    stepNumber: number;
    description?: string;
    isCurrent?: boolean;
    testResult?: TestResult;
}

const DeviceCard: React.FC<DeviceCardProps & { isLandscape?: boolean, standardData?: StandardVO | null }> = ({
                                                                                                                 title,
                                                                                                                 status = 'active',
                                                                                                                 onPress,
                                                                                                                 onRetest,
                                                                                                                 icon = '📱',
                                                                                                                 stepNumber,
                                                                                                                 description,
                                                                                                                 isCurrent = false,
                                                                                                                 testResult,
                                                                                                                 isLandscape = false,
                                                                                                                 standardData = null,
                                                                                                             }) => {
    const isComingSoon = status === 'coming_soon';
    const isCompleted = status === 'completed';

    const getStatusColor = (status: string) => {
        switch (status) {
            case 'normal':
                return '#4CAF50';
            case 'warning':
                return '#FF9800';
            case 'danger':
                return '#F44336';
            case 'untested':
                return '#9E9E9E'; // 灰色表示未测试
            default:
                return '#666';
        }
    };

    const formatTime = (date: Date) => {
        return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    // 根据基准值判断测试结果状态
    const evaluateStatus = (deviceRoute: string, value: any, standardData: StandardVO | null, testResult?: TestResult) => {
        if (!standardData) return 'normal'; // 如果没有基准值，默认为正常

        // 根据不同设备类型判断状态
        switch (deviceRoute) {
            case 'SpO2':
            case 'Cardiovascular_SpO2':
                if (typeof value === 'object') {
                    // 血氧饱和度判断
                    if ('SpO2' in value) {
                        const spo2 = Number(value.SpO2);
                        if (spo2 < standardData.oxygenSaturation * 0.95) return 'danger';
                        if (spo2 < standardData.oxygenSaturation * 0.98) return 'warning';
                        return 'normal';
                    }
                    // 心率判断
                    if ('heartRate' in value) {
                        const hr = Number(value.heartRate);
                        if (hr < standardData.heartRate * 0.7 || hr > standardData.heartRate * 1.3) return 'danger';
                        if (hr < standardData.heartRate * 0.8 || hr > standardData.heartRate * 1.2) return 'warning';
                        return 'normal';
                    }
                }
                break;
            case 'Cardiovascular_BP':
                if (typeof value === 'object') {
                    // 血压判断
                    if ('systolic' in value && 'diastolic' in value) {
                        const systolic = Number(value.systolic);
                        const diastolic = Number(value.diastolic);
                        if (systolic >= 160 || diastolic >= 100) return 'danger';
                        if (systolic >= 140 || diastolic >= 90) return 'warning';
                        return 'normal';
                    }
                }
                break;
            case 'Cardiovascular_ECG':
                if (typeof value === 'object') {
                    // 压力指数和心康指数的状态判断
                    if ('stressIndex' in value) {
                        const stressIndex = Number(value.stressIndex);
                        if (stressIndex > 80) return 'danger';
                        if (stressIndex > 60) return 'warning';
                        return 'normal';
                    }
                    if ('heartAttackIndex' in value) {
                        const heartAttackIndex = Number(value.heartAttackIndex);
                        if (heartAttackIndex > 30) return 'danger';
                        if (heartAttackIndex > 15) return 'warning';
                        return 'normal';
                    }
                }
                return 'normal'; // 默认正常
            case 'Cardiovascular':
                if (typeof value === 'object') {
                    // 血氧饱和度判断 - 支持更多键名
                    const spo2Keys = ['spo2', 'SpO2', 'oxygenSaturation'];
                    for (const key of spo2Keys) {
                        if (key in value) {
                            const spo2 = Number(value[key]);
                            if (spo2 < standardData.oxygenSaturation * 0.95) return 'danger';
                            if (spo2 < standardData.oxygenSaturation * 0.98) return 'warning';
                            return 'normal';
                        }
                    }

                    // 心率判断 - 支持更多键名
                    const heartRateKeys = ['heartRate', 'HeartRate', 'pulse'];
                    for (const key of heartRateKeys) {
                        if (key in value) {
                            const hr = Number(value[key]);
                            if (hr < standardData.heartRate * 0.7 || hr > standardData.heartRate * 1.3) return 'danger';
                            if (hr < standardData.heartRate * 0.8 || hr > standardData.heartRate * 1.2) return 'warning';
                            return 'normal';
                        }
                    }

                    // 血压判断
                    if ('systolic' in value && 'diastolic' in value) {
                        const systolic = Number(value.systolic);
                        const diastolic = Number(value.diastolic);
                        if (systolic >= 160 || diastolic >= 100) return 'danger';
                        if (systolic >= 140 || diastolic >= 90) return 'warning';
                        return 'normal';
                    }

                    // 血压判断后直接进行压力指数判断

                    // 压力指数判断 - 支持更多键名
                    const stressKeys = ['stressIndex', 'hrv'];
                    for (const key of stressKeys) {
                        if (key in value) {
                            const stressIndex = Number(value[key]);
                            if (stressIndex > 80) return 'danger';
                            if (stressIndex > 60) return 'warning';
                            return 'normal';
                        }
                    }

                    // 心康指数判断 - 支持更多键名
                    const heartAttackKeys = ['heartAttackIndex', 'myocardialInfarctionIndex', 'st'];
                    for (const key of heartAttackKeys) {
                        if (key in value) {
                            const heartAttackIndex = Number(value[key]);
                            if (heartAttackIndex > 30) return 'danger';
                            if (heartAttackIndex > 15) return 'warning';
                            return 'normal';
                        }
                    }

                    // 移除了灌注指数判断
                }
                return 'normal'; // 默认正常
            case 'VitalCapacity':
                const vc = Number(value);
                if (vc < standardData.vitalCapacity * 0.7) return 'danger';
                if (vc < standardData.vitalCapacity * 0.85) return 'warning';
                return 'normal';
            case 'Alcohol':
                // 检查是否已测试
                if (testResult && testResult.measurement && testResult.measurement.isTested === false) {
                    return 'untested'; // 未测试状态
                }
                const alcohol = Number(value);
                // 如果酒精值为-1，表示未检测，状态设为异常
                if (alcohol === -1) {
                    return 'danger';
                }
                if (alcohol > standardData.breathAlcohol * 2) return 'danger';
                if (alcohol > standardData.breathAlcohol) return 'warning';
                return 'normal';
            case 'Dynamometer':
                if (typeof value === 'object' && 'grip' in value) {
                    const grip = Number(value.grip);
                    if (grip < standardData.gripStrength * 0.7) return 'danger';
                    if (grip < standardData.gripStrength * 0.85) return 'warning';
                    return 'normal';
                }
                break;
            case 'Reaction':
                const reaction = Number(value);
                if (reaction > standardData.reactionTime * 1.5) return 'danger';
                if (reaction > standardData.reactionTime * 1.2) return 'warning';
                return 'normal';
            default:
                return 'normal';
        }
        return 'normal';
    };

    // 格式化显示测试值
    const formatTestValue = (testResult: TestResult) => {
        const {measurement} = testResult;

        // 特殊处理频闪测试 - 只显示正常与否
        if (testResult.deviceRoute === 'Flicker') {
            const flickerValue = Number(measurement.value);
            const isNormal = flickerValue === 1; // 1表示正常，0表示异常
            return [{
                label: '',
                value: isNormal ? '正常' : '异常',
                unit: ''
            }];
        }

        // 特殊处理心血管设备的心率/血氧测量结果
        if (testResult.deviceRoute === 'Cardiovascular_SpO2') {
            if (typeof measurement.value === 'object') {
                return Object.entries(measurement.value).map(([key, val]) => ({
                    label: key === 'SpO2' ? '血氧' : key === 'heartRate' ? '心率' : key,
                    value: String(val),
                    unit: typeof measurement.unit === 'object' ? measurement.unit[key] : measurement.unit
                }));
            }
        }

        // 特殊处理心血管设备的血压测量结果
        if (testResult.deviceRoute === 'Cardiovascular_BP') {
            if (typeof measurement.value === 'object') {
                return Object.entries(measurement.value).map(([key, val]) => ({
                    label: key === 'systolic' ? '收缩压' : key === 'diastolic' ? '舒张压' : key,
                    value: String(val),
                    unit: typeof measurement.unit === 'object' ? measurement.unit[key] : measurement.unit
                }));
            }
        }

        // 特殊处理心血管设备的HRV/心康指数测量结果
        if (testResult.deviceRoute === 'Cardiovascular_ECG') {
            if (typeof measurement.value === 'object') {
                // 优先显示压力指数和心康指数
                const results = [];
                if ('stressIndex' in measurement.value) {
                    results.push({
                        label: '压力指数',
                        value: String(measurement.value.stressIndex),
                        unit: '%'
                    });
                }
                if ('heartAttackIndex' in measurement.value) {
                    results.push({
                        label: '心康指数',
                        value: String(measurement.value.heartAttackIndex),
                        unit: '%'
                    });
                }
                // 如果没有压力指数和心康指数，则显示导联数据
                if (results.length === 0) {
                    return Object.entries(measurement.value).map(([key, val]) => ({
                        label: key === 'lead1' ? '导联1' : key === 'lead2' ? '导联2' : key === 'lead3' ? '导联3' : key,
                        value: String(val),
                        unit: typeof measurement.unit === 'object' ? measurement.unit[key] : measurement.unit
                    }));
                }
                return results;
            }
        }

        // 特殊处理心血管设备的综合测量结果
        if (testResult.deviceRoute === 'Cardiovascular') {
            if (typeof measurement.value === 'object') {
                // 定义要显示的指标及其默认单位
                const indicators = [
                    {key: 'heartRate', altKeys: ['HeartRate', 'pulse'], label: '心率', defaultUnit: 'bpm'},
                    {key: 'spo2', altKeys: ['SpO2', 'oxygenSaturation'], label: '血氧', defaultUnit: '%'},
                    {key: 'systolic', altKeys: [], label: '收缩压', defaultUnit: 'mmHg'},
                    {key: 'diastolic', altKeys: [], label: '舒张压', defaultUnit: 'mmHg'},
                    {key: 'stressIndex', altKeys: ['hrv'], label: '压力指数', defaultUnit: '%'},
                    {
                        key: 'heartAttackIndex',
                        altKeys: ['myocardialInfarctionIndex', 'st'],
                        label: '心康指数',
                        defaultUnit: '%'
                    }
                ];

                const result = [];

                // 遍历定义的指标，查找对应的值
                for (const indicator of indicators) {
                    let value = null;
                    let unit = '';

                    // 首先尝试使用主键
                    if (measurement.value[indicator.key] !== undefined) {
                        value = measurement.value[indicator.key];
                        unit = typeof measurement.unit === 'object' ? (measurement.unit[indicator.key] || indicator.defaultUnit) : indicator.defaultUnit;
                    }
                    // 然后尝试使用替代键
                    else if (indicator.altKeys && indicator.altKeys.length > 0) {
                        for (const altKey of indicator.altKeys) {
                            if (measurement.value[altKey] !== undefined) {
                                value = measurement.value[altKey];
                                unit = typeof measurement.unit === 'object' ? (measurement.unit[altKey] || indicator.defaultUnit) : indicator.defaultUnit;
                                break;
                            }
                        }
                    }

                    // 如果找到了值，添加到结果中
                    if (value !== null && value !== undefined) {
                        result.push({
                            label: indicator.label,
                            value: String(value),
                            unit: unit
                        });
                    }
                }

                // 如果没有找到定义的指标，则显示所有可用的值
                if (result.length === 0) {
                    return Object.entries(measurement.value).map(([key, val]) => ({
                        label: key === 'SpO2' ? '血氧' :
                            key === 'heartRate' ? '心率' :
                                key === 'systolic' ? '收缩压' :
                                    key === 'diastolic' ? '舒张压' :
                                        key === 'stressIndex' ? '压力指数' :
                                            key === 'heartAttackIndex' ? '心康指数' :
                                                key === 'grip' ? '握力' : key,
                        value: String(val),
                        unit: typeof measurement.unit === 'object' ? measurement.unit[key] : measurement.unit
                    }));
                }

                return result;
            }
        }

        // 特殊处理酒精测试结果
        if (testResult.deviceRoute === 'Alcohol') {
            // 检查是否已测试
            if (measurement.isTested === false) {
                return [{
                    label: '',
                    value: '未测试',
                    unit: ''
                }];
            }
            // 如果酒精值为-1，表示未检测
            if (Number(measurement.value) === -1) {
                return [{
                    label: '',
                    value: '未检测',
                    unit: ''
                }];
            }
            // 已测试，显示实际值
            return [{
                label: '',
                value: String(measurement.value),
                unit: String(measurement.unit)
            }];
        }

        // 处理其他设备的复合值
        if (typeof measurement.value === 'object' && !Array.isArray(measurement.value)) {
            return Object.entries(measurement.value).map(([key, val]) => ({
                label: key === 'SpO2' ? '血氧' : key === 'heartRate' ? '心率' : key === 'systolic' ? '收缩压' : key === 'diastolic' ? '舒张压' : key === 'stressIndex' ? '压力指数' : key === 'heartAttackIndex' ? '心康指数' : key === 'grip' ? '握力' : key,
                value: Number(val) === -2 ? '未检测' : String(val),
                unit: typeof measurement.unit === 'object' ? measurement.unit[key] : measurement.unit
            }));
        } else {
            // 处理单一值
            // 如果值为-2，表示未检测
            if (Number(measurement.value) === -2) {
                return [{
                    label: '',
                    value: '未检测',
                    unit: ''
                }];
            }
            // 已测试，显示实际值
            return [{
                label: '',
                value: String(measurement.value),
                unit: String(measurement.unit)
            }];
        }
    };

    return (
        <View style={[
            styles.card,
            isLandscape && styles.cardLandscape,
            isComingSoon && styles.cardDisabled,
            isCurrent && styles.cardCurrent,
            isCompleted && styles.cardCompleted
        ]}>
            <View style={[
                styles.cardHeaderRow,
                isLandscape && styles.cardHeaderRowLandscape
            ]}>
                <View style={[styles.stepBadge, isLandscape && styles.stepBadgeLandscape]}>
                    <Text style={[styles.stepNumber, isLandscape && styles.stepNumberLandscape]}>
                        步骤 {stepNumber}
                    </Text>
                </View>
                <View style={styles.statusContainer}>
                    {isCurrent && <Text
                        style={[styles.currentStepText, isLandscape && styles.currentStepTextLandscape]}>当前</Text>}
                    {isCompleted && <Text
                        style={[styles.completedStepText, isLandscape && styles.completedStepTextLandscape]}>已完成</Text>}

                    {/* 测试结果状态和时间移到顶部 */}
                    {testResult && (
                        <View style={styles.topResultInfo}>
                            {/*<View style={[styles.statusIndicator, {*/}
                            {/*    backgroundColor: getStatusColor(*/}
                            {/*        standardData ?*/}
                            {/*            evaluateStatus(testResult.deviceRoute, testResult.measurement.value, standardData, testResult) :*/}
                            {/*            testResult.status*/}
                            {/*    )*/}
                            {/*}]}>*/}
                            {/*<Text style={styles.statusText}>*/}
                            {/*    {standardData ?*/}
                            {/*        (evaluateStatus(testResult.deviceRoute, testResult.measurement.value, standardData, testResult) === 'normal' ? '正常' :*/}
                            {/*            evaluateStatus(testResult.deviceRoute, testResult.measurement.value, standardData, testResult) === 'warning' ? '注意' :*/}
                            {/*                evaluateStatus(testResult.deviceRoute, testResult.measurement.value, standardData, testResult) === 'untested' ? '未测试' : '异常') :*/}
                            {/*        (testResult.status === 'normal' ? '正常' :*/}
                            {/*            testResult.status === 'warning' ? '注意' :*/}
                            {/*                testResult.status === 'untested' ? '未测试' : '异常')*/}
                            {/*    }*/}
                            {/*</Text>*/}
                            {/*</View>*/}
                            <Text style={styles.resultTimeTop}>
                                {formatTime(testResult.completedAt)}
                            </Text>
                        </View>
                    )}
                </View>
            </View>

            <Text style={[styles.cardIcon, isLandscape && styles.cardIconLandscape]}>{icon}</Text>
            <Text style={[styles.cardTitle, isLandscape && styles.cardTitleLandscape]}>{title}</Text>

            {description && !testResult && (
                <Text style={[styles.cardDescription, isLandscape && styles.cardDescriptionLandscape]}>
                    {description}
                </Text>
            )}

            {/* 显示测试结果 - 移除时间和状态指示器，因为已经移到顶部 */}
            {testResult && (
                <View style={[styles.resultContainer, isLandscape && styles.resultContainerLandscape]}>
                    {/* 心血管设备使用专用显示组件 */}
                    {(testResult.deviceRoute === 'Cardiovascular' ||
                        testResult.deviceRoute === 'Cardiovascular_SpO2' ||
                        testResult.deviceRoute === 'Cardiovascular_BP' ||
                        testResult.deviceRoute === 'Cardiovascular_ECG') ? (
                        <CardiovascularResultDisplay testResult={testResult} standardData={standardData}/>
                    ) : (
                        formatTestValue(testResult).map((item, index) => {
                            // 根据标准值判断状态
                            const status = standardData && item.label ?
                                evaluateStatus(testResult.deviceRoute, item.value === '未测试' ? {[item.label]: 0} : {[item.label]: Number(item.value)}, standardData, testResult) :
                                (standardData ?
                                    evaluateStatus(testResult.deviceRoute, testResult.measurement.value, standardData, testResult) :
                                    testResult.status);

                            return (
                                <View key={index} style={styles.resultValueContainer}>
                                    {item.label && <Text style={styles.resultLabel}>{item.label}:</Text>}
                                    <Text style={[styles.resultValue, {color: getStatusColor(status)}]}>
                                        {item.value}
                                    </Text>
                                    <Text style={styles.resultUnit}>{item.unit}</Text>

                                    {/* 显示分数而不是基准值 */}
                                    {standardData && testResult.deviceRoute !== 'Flicker' && item.value !== '未测试' && (
                                        <Text style={styles.standardReference}>
                                            {item.label === 'SpO2' ? `(分数: ${calculateSpo2Score(Number(item.value))}分)` :
                                                item.label === 'heartRate' ? `(分数: ${calculateScore(Number(item.value), standardData.heartRate)}分)` :
                                                    item.label === '收缩压' ? `(分数: ${calculateBloodPressureScore(Number(item.value), standardData.systolicPressure)}分)` :
                                                        item.label === '舒张压' ? `(分数: ${calculateBloodPressureScore(Number(item.value), standardData.diastolicPressure)}分)` :
                                                            item.label === '压力指数' ? `(分数: ${100 - Number(item.value)}分)` :
                                                                item.label === '心康指数' ? `(分数: ${100 - Number(item.value) * 2}分)` :
                                                                    // 肺活量测试不显示分数
                                                                    // 酒精测试不显示分数
                                                                    testResult.deviceRoute === 'Dynamometer' && item.label === 'grip' ? `(分数: ${calculateGripStrengthScore(Number(item.value), standardData.gripStrength)}分)` :
                                                                        // 反应时间测试不显示分数
                                                                        testResult.deviceRoute === 'Cardiovascular_SpO2' && item.label === 'SpO2' ? `(分数: ${calculateSpo2Score(Number(item.value))}分)` :
                                                                            testResult.deviceRoute === 'Cardiovascular_SpO2' && item.label === 'heartRate' ? `(分数: ${calculateScore(Number(item.value), standardData.heartRate)}分)` :
                                                                                testResult.deviceRoute === 'Cardiovascular_BP' && item.label === '收缩压' ? `(分数: ${calculateBloodPressureScore(Number(item.value), standardData.systolicPressure)}分)` :
                                                                                    testResult.deviceRoute === 'Cardiovascular_BP' && item.label === '舒张压' ? `(分数: ${calculateBloodPressureScore(Number(item.value), standardData.diastolicPressure)}分)` : ''}
                                        </Text>
                                    )}
                                    {/* 频闪测试不显示分数 */}
                                </View>
                            );
                        })
                    )}
                </View>
            )}

            {/* 操作按钮 */}
            <View style={[styles.buttonContainer, isLandscape && styles.buttonContainerLandscape]}>
                {!isComingSoon && !testResult && (
                    <TouchableOpacity
                        style={[styles.testButton, isLandscape && styles.testButtonLandscape]}
                        onPress={onPress}
                        activeOpacity={0.8}
                    >
                        <Text style={[styles.testButtonText, isLandscape && styles.testButtonTextLandscape]}>
                            开始测试
                        </Text>
                    </TouchableOpacity>
                )}

                {testResult && (
                    <View style={styles.actionButtons}>
                        <TouchableOpacity
                            style={[styles.retestButton, isLandscape && styles.retestButtonLandscape]}
                            onPress={onRetest}
                            activeOpacity={0.8}
                        >
                            <Text style={styles.retestButtonText}>重新测试</Text>
                        </TouchableOpacity>
                    </View>
                )}
            </View>

            {isComingSoon && (
                <View style={styles.comingSoonBadge}>
                    <Text style={styles.comingSoonText}>即将推出</Text>
                </View>
            )}
        </View>
    );
};

// 定义导航参数类型
type RootStackParamList = {
    DevicesList: undefined;
    SpO2: undefined;
    VitalCapacity: undefined;
    Alcohol: undefined;
    Dynamometer: undefined;
};

// 设备列表组件
const DevicesList: React.FC = () => {
    const router = useRouter();
    const [currentStep, setCurrentStep] = useState(1);
    const {testResults, removeTestResult, clearAllResults} = useTestResults();
    const [isSaving, setIsSaving] = useState(false);
    const [screenData, setScreenData] = useState(Dimensions.get('window'));
    const [isLandscape, setIsLandscape] = useState(false);
    const [userInfo, setUserInfo] = useState<UserVo | null>(null);
    const [standardData, setStandardData] = useState<StandardVO | null>(null);
    const [hasTestedToday, setHasTestedToday] = useState<boolean>(false);

    // 加载用户信息和健康指标基准值
    useEffect(() => {
        const loadUserInfoAndStandard = async () => {
            try {
                // 加载用户信息
                const userStr = await AsyncStorage.getItem('TEST_USER');
                let user = null;
                if (userStr) {
                    user = JSON.parse(userStr);
                    setUserInfo(user);
                    // 获取用户健康指标基准值
                    if (user.id) {
                        try {
                            const checked = await DataApi.checkedToday(user.id);
                            console.log(checked)
                            setHasTestedToday(checked.data === true);
                            const response = await StandardApi.getStandard(user.id);
                            console.log(response)
                            if (response.code === 0 && response.data) {
                                setStandardData(response.data);
                            } else {
                                console.warn('获取健康指标基准值失败:', response.msg);
                            }
                        } catch (error) {
                            console.error('获取健康指标基准值出错:', error);
                        }
                    }
                }
            } catch (error) {
                console.error('加载用户信息失败:', error);
            }
        };

        loadUserInfoAndStandard();
    }, []);

    // 监听屏幕方向变化
    useEffect(() => {
        const subscription = Dimensions.addEventListener('change', ({window}) => {
            setScreenData(window);
            setIsLandscape(window.width > window.height);
        });

        // 初始化方向
        const {width, height} = screenData;
        setIsLandscape(width > height);

        return () => subscription?.remove();
    }, []);

    // 保存测试结果到服务器
    const saveTestResults = async () => {
        if (Object.keys(testResults).length === 0) {
            Alert.alert('提示', '暂无测试结果可保存');
            return;
        }

        // 如果用户今天已经测试过，需要确认
        if (hasTestedToday) {
            Alert.alert(
                '确认提交',
                '检测到您今日已进行过测试，确定要重新提交测试结果吗？',
                [
                    {text: '取消', style: 'cancel'},
                    {
                        text: '确定提交',
                        onPress: () => performSave()
                    }
                ]
            );
            return;
        }

        performSave();
    };

    // 执行保存操作
    const performSave = async () => {
        setIsSaving(true);
        try {
            // 获取用户ID
            let user: UserVo = JSON.parse(await AsyncStorage.getItem('TEST_USER') as string);
            if (!user.id) {
                user = JSON.parse(await AsyncStorage.getItem('USER') as string);
            }

            // 如果还没有获取基准值，尝试获取
            if (!standardData && user.id) {
                try {
                    const response = await StandardApi.getStandard(user.id);
                    if (response.code === 0 && response.data) {
                        setStandardData(response.data);
                    }
                } catch (error) {
                    console.error('保存前获取健康指标基准值出错:', error);
                }
            }

            // 转换测试结果为API所需格式
            const healthData: Partial<DataVO> = {
                userId: user?.id.toString() || '',
                recordTime: new Date(),
                heartRate: 0,
                oxygenSaturation: 0,
                systolicPressure: 0,
                diastolicPressure: 0,
                vitalCapacity: 0,
                gripStrength: 0,
                breathAlcohol: -1,
                heartAttackIndex: 0,
                stressIndex: 0,
                reactionTime: 0,
            };
            console.log(JSON.stringify(testResults))
            // 根据测试结果填充数据
            Object.values(testResults).forEach((result: TestResult) => {
                switch (result.deviceRoute) {
                    case 'Cardiovascular':
                        // 从综合心血管数据中补充缺失的指标
                        if (typeof result.measurement.value === 'object') {
                            console.log(result)
                            // 心率
                            healthData.heartRate = Number(result.measurement.value.heartRate);
                            // 血氧
                            healthData.oxygenSaturation = Number(result.measurement.value.spo2);
                            healthData.systolicPressure = Number(result.measurement.value.systolic);
                            healthData.diastolicPressure = Number(result.measurement.value.diastolic)
                            // 压力指数
                            healthData.stressIndex = Number(result.measurement.value.stressIndex);
                            healthData.heartAttackIndex = Number(result.measurement.value.heartAttackIndex);
                        }
                        break;
                    case 'VitalCapacity':
                        healthData.vitalCapacity = Number(result.measurement.value);
                        break;
                    case 'Alcohol':
                        // 检查是否已测试
                        if (result.measurement.isTested === true) {
                            healthData.breathAlcohol = Number(result.measurement.value);
                        }
                        break;
                    case 'Dynamometer':
                        healthData.gripStrength = Number(result.measurement.value);
                        break;
                    case 'Reaction':
                        healthData.reactionTime = Number(result.measurement.value);
                        break;
                }
            });

            // 获取基准值，如果没有则使用默认值
            const baselineValues = {
                heartRate: standardData?.heartRate || 75,
                bloodPressureLow: standardData?.diastolicPressure || 80,
                bloodPressureHigh: standardData?.systolicPressure || 120,
                reactionTime: standardData?.reactionTime || 500,
                gripStrength: standardData?.gripStrength || 40,
                vitalCapacity: standardData?.vitalCapacity || 3500,
            };
            // 计算各项判定分
            // 心率判定分
            const heartRateScore = healthData.heartRate ? calculateScore(healthData.heartRate, baselineValues.heartRate) : 0;
            console.log('心率判定分:', heartRateScore, '心率值:', healthData.heartRate, '基准值:', baselineValues.heartRate);

            // 血压判定分
            const bloodPressureLowScore = healthData.diastolicPressure ?
                calculateBloodPressureScore(healthData.diastolicPressure, baselineValues.bloodPressureLow) : 0;
            const bloodPressureHighScore = healthData.systolicPressure ?
                calculateBloodPressureScore(healthData.systolicPressure, baselineValues.bloodPressureHigh) : 0;
            console.log('血压判定分(低):', bloodPressureLowScore, '舒张压:', healthData.diastolicPressure, '基准值:', baselineValues.bloodPressureLow);
            console.log('血压判定分(高):', bloodPressureHighScore, '收缩压:', healthData.systolicPressure, '基准值:', baselineValues.bloodPressureHigh);

            // 血氧饱和度判定分
            const spo2Score = healthData.oxygenSaturation ? calculateSpo2Score(healthData.oxygenSaturation) : 0;
            console.log('血氧饱和度判定分:', spo2Score, '血氧值:', healthData.oxygenSaturation);

            // 压力指数判定分
            const stressIndexScore = healthData.stressIndex ? calculateStressIndexScore(healthData.stressIndex) : 0;
            console.log('压力指数判定分:', stressIndexScore, '压力指数:', healthData.stressIndex);

            // 心康风险判定分
            const heartAttackRiskScore = healthData.heartAttackIndex ?
                calculateHeartAttackRiskScore(healthData.heartAttackIndex) : 0;
            console.log('心康风险判定分:', heartAttackRiskScore, '心康风险指数:', healthData.heartAttackIndex);

            // 反应时判定分
            const reactionTimeScore = calculateReactionTimeScore(healthData.reactionTime, baselineValues.reactionTime);
            // 握力判定分
            const gripStrengthScore = calculateGripStrengthScore(healthData.gripStrength, baselineValues.gripStrength);
            console.log('握力判定分:', gripStrengthScore, '握力值:', healthData.gripStrength, baselineValues.gripStrength)
            // 临界闪光融合频率判定分 (如果有)
            const flickerResult = testResults['Flicker'];
            const flickerScore = calculateFlickerScore(Number(flickerResult?.measurement?.value));
            // 肺活量判定分
            const vitalCapacityScore = calculateVitalCapacityScore(healthData.vitalCapacity, baselineValues.vitalCapacity);
            // 呼气酒精含量判定分
            const alcoholScore = healthData.breathAlcohol != null ? calculateAlcoholScore(healthData.breathAlcohol) : 0;
            // 计算健康指数、情绪指数、疲劳指数和综合指数
            healthData.health = calculateHealthIndex(
                heartRateScore,
                bloodPressureLowScore,
                bloodPressureHighScore,
                spo2Score,
                heartAttackRiskScore
            );
            console.log('健康指数计算:', healthData.health, '= (', heartRateScore, '+', bloodPressureLowScore, '+', bloodPressureHighScore, '+', spo2Score, ') / 4');

            healthData.mood = stressIndexScore;
            console.log('情绪指数:', healthData.mood);

            healthData.fatigue = calculateFatigueIndex(
                flickerScore,
                alcoholScore,
                reactionTimeScore,
                gripStrengthScore,
                vitalCapacityScore,
            );
            console.log('疲劳指数计算:', healthData.fatigue, '= (', reactionTimeScore, '+', gripStrengthScore, '+', vitalCapacityScore, ') / 3');
            console.log('临界闪光融合频率判定分是否为100:', flickerScore);
            console.log('呼气酒精含量判定分是否为100:', alcoholScore);

            healthData.comprehensive = calculateOverallIndex(
                healthData.health || 0,
                healthData.mood || 0,
                healthData.fatigue || 0
            );
            console.log('综合指数计算:', healthData.comprehensive, '= (', healthData.health || 0, '+', healthData.mood || 0, '+', healthData.fatigue || 0, ') / 3');
            console.log('===== 计算健康指标结束 =====');

            // 设置等级
            healthData.level = calculateLevel(healthData.comprehensive || 0);
            console.log('最终等级:', healthData.level, '综合指数:', healthData.comprehensive);

            // 调用API保存数据前检查数据完整性
            console.log('准备提交的健康数据:', JSON.stringify(healthData, null, 2));

            // 检查关键指标是否为NaN或undefined
            const checkNaN = (value: any, name: string) => {
                if (value === undefined || value === null || isNaN(value)) {
                    console.error(`警告: ${name} 的值无效:`, value);
                    return true;
                }
                return false;
            };

            let hasInvalidData = false;
            if (checkNaN(healthData.health, '健康指数')) hasInvalidData = true;
            if (checkNaN(healthData.mood, '情绪指数')) hasInvalidData = true;
            if (checkNaN(healthData.fatigue, '疲劳指数')) hasInvalidData = true;
            if (checkNaN(healthData.comprehensive, '综合指数')) hasInvalidData = true;

            if (hasInvalidData) {
                console.warn('存在无效数据，可能导致计算错误');

                // 确保所有指标至少有有效值
                healthData.health = healthData.health || 0;
                healthData.mood = healthData.mood || 0;
                healthData.fatigue = healthData.fatigue || 0;
                healthData.comprehensive = healthData.comprehensive || 0;
                healthData.level = healthData.level || 3;
            }
            // const response = await DataApi.createData(healthData as DataVO);
            // 构建导航到结果详情页面的数据，确保键名与ExaminationResults组件匹配
            const navigationHealthData = {
                // 基本指标
                heartRate: healthData.heartRate,
                bloodPressureDiastolic: healthData.diastolicPressure,
                bloodPressureSystolic: healthData.systolicPressure,
                bloodOxygen: healthData.oxygenSaturation,
                stressIndex: healthData.stressIndex,
                heartAttackIndex: healthData.heartAttackIndex,
                reactionTime: healthData.reactionTime,
                gripStrength: healthData.gripStrength,
                flicker: Number(flickerResult?.measurement?.value),
                vitalCapacity: healthData.vitalCapacity,
                alcohol: healthData.breathAlcohol,
                // 计算指数
                healthIndex: healthData.health,
                emotionIndex: healthData.mood,
                fatigueIndex: healthData.fatigue,
                overallIndex: healthData.comprehensive,
                level: healthData.level,
                // 各项判定分
                heartRateScore: heartRateScore,
                bloodPressureLowScore: bloodPressureLowScore,
                bloodPressureHighScore: bloodPressureHighScore,
                spo2Score: spo2Score,
                stressIndexScore: stressIndexScore,
                heartAttackRiskScore: heartAttackRiskScore,
                reactionTimeScore: reactionTimeScore,
                gripStrengthScore: gripStrengthScore,
                flickerScore: flickerScore,
                vitalCapacityScore: vitalCapacityScore,
                alcoholScore: alcoholScore
            };

            const navigationData = {
                healthData: JSON.stringify(navigationHealthData),
                userInfo: JSON.stringify({
                    id: user?.id || 'unknown',
                    nickname: user?.nickname || user?.name || '未知用户',
                    name: user?.name || '未知用户',
                    mobile: user?.mobile || '',
                    sex: user?.sex || 1,
                    avatar: user?.avatar || ''
                })
            };

            // 跳转到结果详情页面
            router.push({
                pathname: '/examination-results',
                params: navigationData
            });
        } catch (error) {
            console.error('保存测试结果失败:', error);
            Alert.alert('错误', `保存失败: ${error instanceof Error ? error.message : '未知错误'}`);
        } finally {
            setIsSaving(false);
        }
    };

    const handleRetest = (deviceRoute: string) => {
        Alert.alert(
            '重新测试',
            '确定要重新进行此项测试吗？',
            [
                {text: '取消', style: 'cancel'},
                {
                    text: '确定',
                    onPress: () => {
                        // 清除当前测试结果
                        removeTestResult(deviceRoute);
                        // 导航到测试页面
                        router.push(`/devices/${deviceRoute}`);
                    }
                }
            ]
        );
    };

    const getDeviceStatus = (route: string, stepNumber: number) => {
        if (testResults[route]) return 'completed';
        if (stepNumber === currentStep) return 'active';
        return 'active';
    };

    const devices = [
        {
            title: '心血管检测',
            icon: '💓',
            route: 'Cardiovascular' as const,
            component: CardiovascularDevice,
            description: '心率/血压/血氧/压力/心康检测',
            stepNumber: 1,
        },
        {
            title: '反应速度检测',
            icon: '⚡',
            route: 'Reaction' as const,
            description: '测量反应速度和敏捷性',
            stepNumber: 2,
        },
        {
            title: '握力检测',
            icon: '💪',
            route: 'Dynamometer' as const,
            component: DynamometerDevice,
            description: '测量手部握力强度',
            stepNumber: 3,
        },
        {
            title: '临界频闪检测',
            icon: '💡',
            route: 'Flicker' as const,
            description: '测试频闪感知能力',
            stepNumber: 4,
        },
        {
            title: '肺活量检测',
            icon: '🫁',
            route: 'VitalCapacity' as const,
            component: VitalCapacityDevice,
            description: '测量肺部呼吸功能',
            stepNumber: 5,
        },
        {
            title: '呼气酒精检测',
            icon: '🍺',
            route: 'Alcohol' as const,
            component: AlcoholDevice,
            description: '检测体内酒精含量',
            stepNumber: 6,
        },
    ];

    const completedCount = Object.keys(testResults).length;
    const totalTests = devices.filter(d => d.route).length;

    // 横屏时的优化网格布局渲染 - 针对平板横屏优化
    const renderLandscapeGrid = () => {
        const itemsPerRow = 3; // 三列布局适合平板横屏
        const rows = [];

        for (let i = 0; i < devices.length; i += itemsPerRow) {
            const rowDevices = devices.slice(i, i + itemsPerRow);
            rows.push(
                <View key={i} style={styles.landscapeRow}>
                    {rowDevices.map((device, index) => (
                        <View key={device.stepNumber} style={styles.landscapeCardContainer}>
                            <DeviceCard
                                title={device.title}
                                icon={device.icon}
                                status={device.route ? getDeviceStatus(device.route, device.stepNumber) : 'coming_soon'}
                                onPress={() => device.route && router.push(`/devices/${device.route}`)}
                                onRetest={() => device.route && handleRetest(device.route)}
                                stepNumber={device.stepNumber}
                                description={device.description}
                                isCurrent={currentStep === device.stepNumber}
                                testResult={device.route ? testResults[device.route] : undefined}
                                isLandscape={isLandscape}
                                standardData={standardData}
                            />
                        </View>
                    ))}
                    {/* 填充空白位置保持对齐 */}
                    {Array.from({length: itemsPerRow - rowDevices.length}).map((_, emptyIndex) => (
                        <View key={`empty-${emptyIndex}`} style={styles.landscapeCardContainer}/>
                    ))}
                </View>
            );
        }
        return rows;
    };

    return (
        <SafeAreaView style={styles.safeArea}>
            <ScrollView
                style={styles.container}
                contentContainerStyle={[
                    styles.scrollContent,
                    isLandscape && styles.scrollContentLandscape
                ]}
            >
                {/* 设备列表 - 根据屏幕方向选择布局 */}
                {isLandscape ? (
                    <View className="mt-2" style={styles.landscapeDashboard}>
                        {/* 顶部信息栏 - 横屏优化 */}
                        <View style={styles.topInfoBarLandscape}>
                            <View style={styles.personInfoLandscape}>
                                <View style={styles.avatarNameContainer}>
                                    {userInfo?.avatar && userInfo.avatar.length > 0 ? (
                                        <Image
                                            source={{uri: userInfo.avatar}}
                                            style={styles.avatarImage}
                                            onError={(e) => console.error('Avatar load error:', e.nativeEvent.error)}
                                        />
                                    ) : (
                                        <View style={styles.avatarPlaceholder}>
                                            <Text style={styles.avatarPlaceholderText}>
                                                {userInfo?.nickname?.[0] || '?'}
                                            </Text>
                                        </View>
                                    )}
                                    <Text style={styles.personNameLandscape}>
                                        {userInfo?.nickname || '未知用户'} ({userInfo?.sex === 1 ? '男' : '女'})
                                    </Text>
                                </View>
                                <Text style={styles.personIdLandscape}>
                                    手机: {userInfo?.mobile ? `${userInfo.mobile.substring(0, 3)}****${userInfo.mobile.substring(7)}` : ''}
                                </Text>
                                {/* 在个人信息区域显示"今日已测过"标识 */}
                                {hasTestedToday && (
                                    <View style={styles.testedTodayBadgeLandscapeInInfo}>
                                        <Text style={styles.testedTodayTextLandscape}>今日已测过</Text>
                                    </View>
                                )}
                            </View>
                            <View style={styles.progressInfoLandscape}>
                                <Text style={styles.progressTextLandscape}>
                                    测试进度: <Text
                                    style={{fontWeight: 'bold', color: '#0a7ea4'}}>{completedCount}</Text>/{totalTests}
                                </Text>
                                <View style={styles.progressBarLandscape}>
                                    <View style={[
                                        styles.progressFillLandscape,
                                        {width: `${(completedCount / totalTests) * 100}%`}
                                    ]}/>
                                </View>
                                <Text style={styles.progressPercentageLandscape}>
                                    完成率 {Math.round((completedCount / totalTests) * 100)}%
                                </Text>
                            </View>
                            <View style={styles.actionButtonsLandscape}>
                                {Object.keys(testResults).length > 0 && (
                                    <TouchableOpacity
                                        style={[styles.saveButtonLandscape, isSaving && styles.saveButtonDisabled]}
                                        onPress={saveTestResults}
                                        disabled={isSaving}
                                        activeOpacity={0.8}
                                    >
                                        <View style={styles.saveButtonInner}>
                                            <Text style={styles.saveButtonLandscapeText}>
                                                {isSaving ? '保存中...' : '保存结果'}
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                )}
                            </View>
                        </View>

                        {/* 设备网格 - 横屏优化布局 */}
                        <View style={styles.devicesGridLandscape}>
                            {renderLandscapeGrid()}
                        </View>
                    </View>
                ) : (
                    <View style={styles.timelineWrap}>
                        {devices.map((device, index) => (
                            <View key={index} style={styles.timelineItemBox}>
                                {/* 时间轴竖线 */}
                                {index > 0 && <View style={styles.timelineConnector}/>}
                                {/* 步骤卡片 */}
                                <DeviceCard
                                    title={device.title}
                                    icon={device.icon}
                                    status={device.route ? getDeviceStatus(device.route, device.stepNumber) : 'coming_soon'}
                                    onPress={() => device.route && (navigation as any).navigate(`devices/${device.route}`)}
                                    onRetest={() => device.route && handleRetest(device.route)}
                                    stepNumber={device.stepNumber}
                                    description={device.description}
                                    isCurrent={currentStep === device.stepNumber}
                                    testResult={device.route ? testResults[device.route] : undefined}
                                    isLandscape={false}
                                    standardData={standardData}
                                />
                            </View>
                        ))}
                    </View>
                )}

                {/* 保存结果按钮 - 仅在竖屏时显示 */}
                {!isLandscape && (
                    <>
                        {/* 竖屏模式下显示用户信息和进度 */}
                        {userInfo && (
                            <View style={styles.userInfoContainer}>
                                <View style={styles.avatarNameContainer}>
                                    {userInfo?.avatar && userInfo.avatar.length > 0 ? (
                                        <Image
                                            source={{uri: userInfo.avatar}}
                                            style={styles.avatarImage}
                                            onError={(e) => console.error('Avatar load error:', e.nativeEvent.error)}
                                        />
                                    ) : (
                                        <View style={styles.avatarPlaceholder}>
                                            <Text style={styles.avatarPlaceholderText}>
                                                {userInfo?.nickname?.[0] || '?'}
                                            </Text>
                                        </View>
                                    )}
                                    <Text style={styles.userNameText}>
                                        {userInfo?.nickname || '未知用户'} ({userInfo?.sex === 1 ? '男' : '女'})
                                    </Text>
                                </View>
                                <Text
                                    style={styles.userPhoneText}>手机: {userInfo?.mobile ? `${userInfo.mobile.substring(0, 3)}****${userInfo.mobile.substring(7)}` : ''}</Text>

                                {/* 添加进度条显示 */}
                                <View style={styles.progressContainer}>
                                    <View style={styles.progressTextContainer}>
                                        <Text style={styles.progressText}>
                                            测试进度: <Text style={{
                                            fontWeight: 'bold',
                                            color: '#0a7ea4'
                                        }}>{completedCount}</Text>/{totalTests}
                                        </Text>
                                        <Text style={styles.progressPercentage}>
                                            {Math.round((completedCount / totalTests) * 100)}%
                                        </Text>
                                        {hasTestedToday && (
                                            <View style={styles.testedTodayBadge}>
                                                <Text style={styles.testedTodayText}>今日已测过</Text>
                                            </View>
                                        )}
                                    </View>
                                    <View style={styles.progressBar}>
                                        <View style={[
                                            styles.progressFill,
                                            {width: `${(completedCount / totalTests) * 100}%`}
                                        ]}/>
                                    </View>
                                </View>
                            </View>
                        )}

                        {/* 保存按钮 */}
                        {Object.keys(testResults).length > 0 && (
                            <View style={styles.saveButtonContainer}>
                                <TouchableOpacity
                                    style={[
                                        styles.saveButton,
                                        isSaving && styles.saveButtonDisabled
                                    ]}
                                    onPress={saveTestResults}
                                    disabled={isSaving}
                                    activeOpacity={0.8}
                                >
                                    <View style={styles.saveButtonInner}>
                                        <Text style={styles.saveIconText}>📋</Text>
                                        <Text style={styles.saveButtonText}>
                                            {isSaving ? '保存中...' : '保存测试结果'}
                                        </Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        )}
                    </>
                )}
            </ScrollView>
        </SafeAreaView>
    );
};

// 移除Stack相关内容，只保留DevicesList
export default DevicesList;

// 样式定义 - 针对平板横屏优化
const styles = StyleSheet.create({
    safeArea: {
        flex: 1,
        backgroundColor: '#f6f8fa',
    },
    container: {
        flex: 1,
        backgroundColor: '#f6f8fa',
    },
    scrollContent: {
        paddingBottom: 40,
    },
    scrollContentLandscape: {
        paddingHorizontal: 30,
        paddingVertical: 20,
    },

    // 竖屏时间轴布局
    timelineWrap: {
        padding: 18,
        paddingTop: 8,
    },
    timelineItemBox: {
        marginBottom: 28,
        alignItems: 'center',
        position: 'relative',
    },
    timelineConnector: {
        position: 'absolute',
        top: -18,
        left: '50%',
        marginLeft: -2,
        height: 36,
        width: 4,
        backgroundColor: '#e0e7ef',
        zIndex: 0,
        borderRadius: 2,
    },

    // 横屏仪表板布局
    landscapeDashboard: {
        flex: 1,
        gap: 20,
    },
    topInfoBarLandscape: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: '#fff',
        paddingHorizontal: 24,
        paddingVertical: 16,
        borderRadius: 16,
        shadowColor: '#0a7ea4',
        shadowOffset: {width: 0, height: 4},
        shadowOpacity: 0.08,
        shadowRadius: 8,
        elevation: 4,
        minHeight: 80,
    },
    personInfoLandscape: {
        flex: 1,
    },
    personNameLandscape: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 4,
    },
    personIdLandscape: {
        fontSize: 14,
        color: '#666',
    },
    progressInfoLandscape: {
        flex: 1,
        alignItems: 'center',
        paddingHorizontal: 20,
    },
    progressTextLandscape: {
        fontSize: 16,
        fontWeight: '600',
        color: '#333',
        marginBottom: 10,
        letterSpacing: 0.5,
    },
    progressBarLandscape: {
        width: 180,
        height: 10,
        backgroundColor: '#f0f0f0',
        borderRadius: 5,
        overflow: 'hidden',
        marginBottom: 8,
        borderWidth: 1,
        borderColor: '#e0e0e0',
    },
    progressFillLandscape: {
        height: '100%',
        backgroundColor: '#0a7ea4',
        borderRadius: 4,
        shadowColor: '#0a7ea4',
        shadowOffset: {width: 0, height: 0},
        shadowOpacity: 0.3,
        shadowRadius: 3,
    },
    progressPercentageLandscape: {
        fontSize: 15,
        fontWeight: 'bold',
        color: '#0a7ea4',
        letterSpacing: 0.5,
    },
    actionButtonsLandscape: {
        flex: 1,
        alignItems: 'flex-end',
    },
    saveButtonLandscape: {
        backgroundColor: '#0a7ea4',
        paddingVertical: 12,
        paddingHorizontal: 20,
        borderRadius: 12,
        shadowColor: '#0a7ea4',
        shadowOffset: {width: 0, height: 3},
        shadowOpacity: 0.25,
        shadowRadius: 6,
        elevation: 4,
        minWidth: 140,
    },
    saveButtonInner: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    saveIconText: {
        fontSize: 18,
        marginRight: 8,
        color: '#fff',
    },
    saveButtonLandscapeText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
        textAlign: 'center',
    },

    // 横屏设备网格
    devicesGridLandscape: {
        flex: 1,
        paddingHorizontal: 10,
    },
    landscapeRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 20,
        gap: 20,
    },
    landscapeCardContainer: {
        flex: 1,
        alignItems: 'center',
        maxWidth: '32%',
    },

    // 基础卡片样式
    card: {
        width: Dimensions.get('window').width - 56,
        backgroundColor: '#fff',
        borderRadius: 18,
        paddingVertical: 12,
        paddingHorizontal: 16,
        alignItems: 'center',
        shadowColor: '#0a7ea4',
        shadowOffset: {width: 0, height: 8},
        shadowOpacity: 0.06,
        shadowRadius: 10,
        elevation: 4,
        borderWidth: 0,
        borderColor: 'transparent',
        position: 'relative',
        minHeight: 120,
    },
    cardLandscape: {
        width: '100%',
        maxWidth: 420,
        minHeight: 220,
        paddingVertical: 16,
        paddingHorizontal: 20,
        shadowColor: '#0a7ea4',
        shadowOffset: {width: 0, height: 6},
        shadowOpacity: 0.12,
        shadowRadius: 12,
        elevation: 6,
        borderRadius: 20,
    },
    cardDisabled: {
        opacity: 0.6,
        backgroundColor: '#f8f8f8',
        shadowOpacity: 0.03,
    },
    cardCurrent: {
        borderWidth: 2,
        borderColor: '#0a7ea4',
        shadowOpacity: 0.18,
        shadowRadius: 24,
        elevation: 16,
        backgroundColor: '#f8fcff',
    },
    cardCompleted: {
        borderWidth: 1,
        borderColor: '#4CAF50',
        backgroundColor: '#f8fff8',
    },

    // 卡片头部
    cardHeaderRow: {
        flexDirection: 'row',
        alignItems: 'center',
        width: '100%',
        marginBottom: 8,
        justifyContent: 'space-between',
    },
    cardHeaderRowLandscape: {
        marginBottom: 12,
    },
    statusContainer: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    stepBadge: {
        backgroundColor: '#e0f7fa',
        paddingHorizontal: 14,
        paddingVertical: 4,
        borderRadius: 12,
    },
    stepBadgeLandscape: {
        paddingHorizontal: 16,
        paddingVertical: 6,
        borderRadius: 14,
    },
    stepNumber: {
        color: '#0a7ea4',
        fontWeight: 'bold',
        fontSize: 13,
        letterSpacing: 1,
    },
    stepNumberLandscape: {
        fontSize: 14,
    },
    currentStepText: {
        color: '#fff',
        backgroundColor: '#0a7ea4',
        fontSize: 12,
        fontWeight: 'bold',
        borderRadius: 8,
        paddingHorizontal: 8,
        paddingVertical: 2,
        overflow: 'hidden',
    },
    currentStepTextLandscape: {
        fontSize: 13,
        paddingHorizontal: 10,
        paddingVertical: 3,
        borderRadius: 10,
    },
    completedStepText: {
        color: '#fff',
        backgroundColor: '#4CAF50',
        fontSize: 12,
        fontWeight: 'bold',
        borderRadius: 8,
        paddingHorizontal: 8,
        paddingVertical: 2,
        overflow: 'hidden',
    },
    completedStepTextLandscape: {
        fontSize: 13,
        paddingHorizontal: 10,
        paddingVertical: 3,
        borderRadius: 10,
    },

    // 卡片内容
    cardIcon: {
        fontSize: 36,
        marginBottom: 6,
        marginTop: 0,
    },
    cardIconLandscape: {
        fontSize: 42,
        marginBottom: 8,
        marginTop: 2,
    },
    cardTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        textAlign: 'center',
        color: '#222',
        marginBottom: 3,
        letterSpacing: 0.5,
    },
    cardTitleLandscape: {
        fontSize: 20,
        marginBottom: 4,
        letterSpacing: 0.5,
    },
    cardDescription: {
        fontSize: 14,
        textAlign: 'center',
        color: '#666',
        marginTop: 1,
        marginBottom: 1,
        lineHeight: 18,
    },
    cardDescriptionLandscape: {
        fontSize: 15,
        lineHeight: 20,
        marginTop: 2,
        marginBottom: 2,
    },

    // 心血管设备专用样式
    cardioContainer: {
        flexDirection: 'row',
        flexWrap: 'nowrap',
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        marginTop: 0,
        marginBottom: 0,
        alignSelf: 'center',
    },
    cardioItem: {
        flex: 1,
        alignItems: 'center',
        marginBottom: 0,
        paddingVertical: 0,
        paddingHorizontal: 0,
        borderRadius: 2,
        backgroundColor: 'transparent',
    },
    cardioLabel: {
        fontSize: 8,
        color: '#666',
        marginBottom: 0,
    },
    cardioValue: {
        fontSize: 12,
        fontWeight: 'bold',
    },

    // 测试结果显示
    resultContainer: {
        alignItems: 'center',
        marginTop: 8,
        marginBottom: 10,
        width: '100%',
    },
    resultContainerLandscape: {
        marginTop: 12,
        marginBottom: 12,
    },
    resultValueContainer: {
        flexDirection: 'row',
        alignItems: 'baseline',
        marginBottom: 3,
        justifyContent: 'center',
        flexWrap: 'wrap',
    },
    resultLabel: {
        fontSize: 16,
        color: '#333',
        fontWeight: '600',
        marginRight: 4,
    },
    resultValue: {
        fontSize: 24,
        fontWeight: 'bold',
        marginRight: 4,
    },
    resultUnit: {
        fontSize: 16,
        color: '#666',
        fontWeight: '500',
    },
    standardReference: {
        fontSize: 12,
        color: '#666',
        marginLeft: 8,
        fontStyle: 'italic',
    },
    resultTime: {
        fontSize: 12,
        color: '#999',
        marginBottom: 6,
    },
    resultTimeTop: {
        fontSize: 11,
        color: '#666',
        marginLeft: 6,
    },
    statusIndicator: {
        paddingHorizontal: 12,
        paddingVertical: 4,
        borderRadius: 12,
    },
    statusText: {
        color: '#fff',
        fontSize: 12,
        fontWeight: 'bold',
    },
    topResultInfo: {
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 8,
    },

    // 按钮样式
    buttonContainer: {
        width: '100%',
        marginTop: 6,
    },
    buttonContainerLandscape: {
        marginTop: 10,
    },
    testButton: {
        backgroundColor: '#0a7ea4',
        paddingVertical: 12,
        paddingHorizontal: 24,
        borderRadius: 12,
        alignItems: 'center',
    },
    testButtonLandscape: {
        paddingVertical: 14,
        paddingHorizontal: 28,
        borderRadius: 14,
    },
    testButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    testButtonTextLandscape: {
        fontSize: 17,
    },
    actionButtons: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        gap: 12,
    },
    retestButton: {
        flex: 1,
        backgroundColor: '#FF9800',
        paddingVertical: 10,
        paddingHorizontal: 16,
        borderRadius: 10,
        alignItems: 'center',
    },
    retestButtonLandscape: {
        paddingVertical: 12,
        paddingHorizontal: 18,
        borderRadius: 12,
    },
    retestButtonText: {
        color: '#fff',
        fontSize: 14,
        fontWeight: 'bold',
    },
    detailButton: {
        flex: 1,
        backgroundColor: '#f0f0f0',
        paddingVertical: 10,
        paddingHorizontal: 16,
        borderRadius: 10,
        alignItems: 'center',
    },
    detailButtonLandscape: {
        paddingVertical: 12,
        paddingHorizontal: 18,
        borderRadius: 12,
    },
    detailButtonText: {
        color: '#333',
        fontSize: 14,
        fontWeight: 'bold',
    },

    // 即将推出标识
    comingSoonBadge: {
        position: 'absolute',
        top: 12,
        right: 16,
        backgroundColor: '#ffd700',
        paddingHorizontal: 10,
        paddingVertical: 4,
        borderRadius: 12,
    },
    comingSoonText: {
        fontSize: 13,
        color: '#333',
        fontWeight: 'bold',
    },

    // 竖屏保存按钮
    saveButtonContainer: {
        paddingHorizontal: 18,
        paddingVertical: 20,
        paddingBottom: 40,
    },
    saveButton: {
        backgroundColor: '#0a7ea4',
        paddingVertical: 16,
        paddingHorizontal: 24,
        borderRadius: 12,
        alignItems: 'center',
        shadowColor: '#0a7ea4',
        shadowOffset: {width: 0, height: 4},
        shadowOpacity: 0.3,
        shadowRadius: 8,
        elevation: 6,
    },
    saveButtonDisabled: {
        backgroundColor: '#cccccc',
        shadowOpacity: 0.1,
    },
    saveButtonText: {
        color: '#fff',
        fontSize: 18,
        fontWeight: 'bold',
        letterSpacing: 1,
    },
    // 竖屏模式下的用户信息样式
    userInfoContainer: {
        backgroundColor: '#fff',
        borderRadius: 12,
        padding: 16,
        marginHorizontal: 18,
        marginBottom: 20,
        shadowColor: '#0a7ea4',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    userNameText: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
    },
    userPhoneText: {
        fontSize: 14,
        color: '#666',
        marginTop: 4,
        marginLeft: 46, // 与头像对齐
    },

    // 进度相关样式
    progressContainer: {
        marginTop: 16,
        width: '100%',
        alignItems: 'center',
    },
    progressBar: {
        width: '80%',
        height: 6,
        backgroundColor: 'rgba(255,255,255,0.3)',
        borderRadius: 3,
        overflow: 'hidden',
    },
    progressFill: {
        height: '100%',
        backgroundColor: '#fff',
        borderRadius: 3,
    },
    progressText: {
        color: 'rgba(255,255,255,0.9)',
        fontSize: 14,
        marginTop: 8,
        fontWeight: '600',
    },
    // 头像相关样式
    avatarNameContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 4,
    },
    avatarImage: {
        width: 36,
        height: 36,
        borderRadius: 18,
        marginRight: 10,
    },
    avatarPlaceholder: {
        width: 36,
        height: 36,
        borderRadius: 18,
        backgroundColor: '#e0e0e0',
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: 10,
    },
    avatarPlaceholderText: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#666',
    },

    // 今日已测过提示样式
    testedTodayBadgeLandscape: {
        backgroundColor: '#FFF3CD',
        borderColor: '#FFEAA7',
        borderWidth: 1,
        paddingHorizontal: 12,
        paddingVertical: 6,
        borderRadius: 12,
        marginTop: 8,
    },
    testedTodayBadgeLandscapeInInfo: {
        backgroundColor: '#FFF3CD',
        borderColor: '#FFEAA7',
        borderWidth: 1,
        paddingHorizontal: 12,
        paddingVertical: 4,
        borderRadius: 12,
        marginTop: 8,
        alignSelf: 'flex-start',
    },
    testedTodayTextLandscape: {
        color: '#856404',
        fontSize: 12,
        fontWeight: 'bold',
    },
    testedTodayBadge: {
        backgroundColor: '#FFF3CD',
        borderColor: '#FFEAA7',
        borderWidth: 1,
        paddingHorizontal: 10,
        paddingVertical: 4,
        borderRadius: 10,
        marginLeft: 12,
    },
    testedTodayText: {
        color: '#856404',
        fontSize: 11,
        fontWeight: 'bold',
    },
    progressTextContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        width: '100%',
        marginBottom: 8,
    },
    progressPercentage: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#0a7ea4',
    },
});
